package org.wenhua.yuan.and.util

import android.app.Activity
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.WindowManager

/**
 * 沉浸式状态栏设置工具
 */
object ImmersiveStatusBar {

    /**
     * @param context
     * @param darkContent true=白底黑字， false=黑底白字
     * @param statusBarColor  状态栏背景色
     * @param translucent 沉浸式效果，是否将页面布局延伸到状态栏下
     * darkContent=translucent=true时，通过设置statusBarColor修改状态栏背景色；
     *
     */
    fun setStatusBar (
        context: Activity,
        darkContent: Boolean,
        statusBarColor: Int = Color.WHITE,
        translucent: Boolean) {

        val window = context.window;
        val decorView = window.decorView;
        var visibility = decorView.systemUiVisibility

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 请求系统绘制状态栏的背景色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            // 这里需要清除FLAG_TRANSLUCENT_STATUS=>>FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS和FLAG_TRANSLUCENT_STATUS不能同时出现
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.statusBarColor = statusBarColor
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            visibility = if (darkContent) {
                // 浅色主题（白底黑色字体）
                visibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                // 深色主题（黑底白色字体）
                visibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
            }
        }

        if (translucent) {
            // fix：当View布局会延伸到状态栏之下，而状态栏图标消失
            visibility = visibility or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }

        decorView.systemUiVisibility = visibility
    }
}